<template>
	<div class="wt-model-field-input">
		<template v-if="!field.dependingField || form[field.dependingField.name] != ''">
		<component
			v-if="field.customComponent"
			:ref="field.tableName"
			v-model="form[field.tableName]"
			:class="getFieldClass(field)"
			:is="field.customComponent"
			:field="field"
			:form="form"
			:params-data="paramsData"
		></component>
		<el-input 
			v-else-if="field.type == types.text" 
			v-model="form[field.tableName]" 
			:class="getFieldClass(field)"
			:disabled="field.readonly"
		></el-input>
		<el-input 
			v-else-if="field.type == types.textarea" 
			v-model="form[field.tableName]" 
			type="textarea"
			:autosize="{ minRows: 2, maxRows: 6 }" 
			:rows="2" 
			:class="getFieldClass(field)"
			:disabled="field.readonly">
		</el-input>
		<el-date-picker 
			v-else-if="field.type == types.date" 
			v-model="form[field.tableName]" 
			type="date"
			:disabled="field.readonly"
			:picker-options="currentFieldHelper ? currentFieldHelper.pickerOptions : null"
		></el-date-picker>
		<wt-select 
			:ref="field.tableName"
			:getCurrentValue="field.getCurrentValue"
			v-else-if="field.type == types.select" 
			v-model="form[field.tableName]" 
			:multiple="field.multiple" 
			:options="field.options" 
			:remote='field.query !== undefined' 
			:query="field.query" 
			:params-data="paramsData"
			:class="getFieldClass(field)"
			:disabled="field.readonly"
			:parse="field.parse"
		></wt-select>
		<wt-autocomplete 
			v-else-if="field.type == types.autocomplete" 
			v-model="form[field.tableName]" 
			:multiple="field.multiple" 
			:query="field.query" 
			:customResultParser="field.customResultParser"
			:customOptionComponent="field.customOptionComponent"
			:profixSelectedDisplayInUIFun="field.profixSelectedDisplayInUIFun"
			:allow-add="field.query.allowAdd" 
			:disabled="field.readonly"
			:params-data="paramsData"
			:allowUseWithoutAdd="field.allowUseWithoutAdd"
			:selectValuefield="field.selectValuefield"
		></wt-autocomplete>
		<el-input 
			v-else-if="field.type == types.number" 
			v-model.number="form[field.tableName]" 
			:class="getFieldClass(field)"
			step="0.01"
			:disabled="field.readonly"
		></el-input>
		<wt-image-selector
			:ref="field.tableName"
			v-else-if="field.type == types.images"
			:value="form[field.tableName]"
			@input="value => { form[field.name] = value }"
			:upload-config="field.upload"
			:auto-upload="false"
			:parent-id="currentId"
			@stop="stop"
			:disabled="field.readonly"
		></wt-image-selector>
		<wt-model-link-selector
			:ref="field.tableName"
			v-else-if="field.type == types.links"
			v-model="form[field.tableName]"
			:linked-model="field.linkedModel"
			:upload-config="field.upload"
			:delete-config="field.delete"
			:parent-id="currentId"
			:params-data="paramsData"
			:disabled="field.readonly"
			:multiple="field.multiple"
			:field="field"
		></wt-model-link-selector>
		<label 
			v-if="field.unit" 
			class="wt-label"
		>{{ field.unit }}</label>
		<component
			v-if="field.appendComponent"
			:ref="field.tableName"
			v-model="form[field.tableName]"
			:class="getFieldClass(field)"
			:is="field.appendComponent"
			:field="field"
			:form="form"
			:params-data="paramsData"
			:helpers="helpers"
		></component>
		</template>
		<template v-else>{{field.dependingField.message}}
		</template>
	</div>
</template>
<script>
	/**
	 * 数据模型通用input组件
	 */
	import Vue from 'vue';
	import ElementUI from 'element-ui';
	import Fields from '../utils/wt-model-field';
	import Select from './wt-select';
	import Autocomplete from './wt-autocomplete';
	import ImageSelector from './wt-image-selector';
	import ModelLink from './wt-model-link-selector';

	Vue.use(ElementUI);
	Vue.component(Select.name, Select);
	Vue.component(Autocomplete.name, Autocomplete);
	Vue.component(ImageSelector.name, ImageSelector);
	Vue.component(ModelLink.name, ModelLink);

	export default {
		name: 'wt-model-field-input',
		props: {
			// 字段对象（包含字段配置信息）
			field: {
				type: Object,
				required: true,
			},
			// 表单数据对象
			form: {
				type: Object,
				required: true,
			},
			currentId: {
				type: [Object, String, Number],
				default: null
			},
			paramsData: {
				type: Object,
				default: null
			},
			helpers: {
				type: Object,
				default: function() {
					return {};
				}
			},
		},
		data() {
			return {
				types: Fields.types,
                fieldHelper:{
					date:function(){
                        let options = this.helpers[this.field.tableName];
                        //兼容原有的规则
                        let origin_disabledDate;
                        if(options){
                            origin_disabledDate = options.pickerOptions.disabledDate;
                        }else{
                            options = {}
                            origin_disabledDate = function(){
                                return true
                            };
                        }
                        options.disabledDate = time => {
                            //利用现在的时间计算今天结束时的时间
                            let now = new Date(),
                                y = now.getFullYear(),
                                m = now.getMonth(),
                                d = now.getDate(),
                                todayEndTime = new Date(y,m,d).getTime(),//今天结束时的时间
                                inputTime = time.getTime(),
								birthday = this.paramsData.patientBirthday
                            if((birthday > inputTime || inputTime > todayEndTime) && origin_disabledDate()){
                                return true
                            }else{
                                return false
                            }
                        }
                        return {'pickerOptions':options};
					}.bind(this),
					//其他辅助验证方法
					//...
				}
			}
		},
		computed: {
			dependingField: function() {
				return this.field.dependingField ? this.form[this.field.dependingField.name] : null;
			},
			/*currentFieldHelper,辅助表单验证，内部根据表单类型从fieldHelper中获取具体的表单验证方法*/
			currentFieldHelper: function() {
			    var res;
				switch(this.field.type){
				    //其他case...
					case 6://日期
                        res = this.fieldHelper.date();
                        break;
					default:
					    res = {}
					    break;
				}
				return res;
			}
		},
		watch: {
			'dependingField'(val, oldValue) {
				if (val != null) {
					this.updateParamsData();
					this.form[this.field.tableName] = '';
					// 延迟一帧执行，因为有可能ref的组件还未被绑定，等待下一帧绑定后再调用reset
					this.$nextTick(() => {
						let ref = this.getRef();
						if (ref && ref.reset) {
							ref.reset();	
						}
					});
				}
				this.$emit('grade',val)
			}
		},
		methods: {
			load() {
				let ref = this.getRef();
				if (ref && ref.load) {
					ref.load();
				}
			},
			getRef() {
				let ref = this.$refs[this.field.tableName];
				if (ref) {
					if (Array.isArray(ref)) {
						ref = ref[0];
					}
				}
				return ref;
			},
			submit(successCallback, errorCallback) {
				let ref = this.getRef();
				if (ref && ref.submit) {
					ref.submit(successCallback, errorCallback);
				}
			},
			updateParamsData() {
				if (this.field.dependingField && this.field.dependingField.paramName) {
					this.paramsData[this.field.dependingField.paramName]	= this.dependingField;
				}
			},
			getFieldClass(field) {
				return field.formSize ? 'wt-field-' + field.formSize : '';
			},
			stop(){
				this.$emit('stop');
			},
			handleImagesChange(data){
				this.$emit('image', {data:data.data});
			}
		},
		created() {
			this.updateParamsData();
		}
	}
</script>
<style scoped>
	.wt-field-mini {
		width: 100%;
		max-width: 90px;
	}
	.wt-field-small {
		width: 100%;
		max-width: 180px;
	}
	.wt-field-normal {
		width: 100%;
		max-width: 360px;
	}
	.wt-field-large {
		width: 100%;
	}
	.wt-label {
		text-align: left;
		vertical-align: middle;
		font-size: 14px;
		color: #48576a;
		line-height: 1;
		padding: 11px 12px 11px 0;
		box-sizing: border-box;
	}
</style>